package com.mainbo.modular.system.controller;

import cn.stylefeng.roses.core.base.controller.BaseController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.core.common.constant.ConfigUtils;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.util.Result;
import com.mainbo.modular.jms.JmsService;
import com.mainbo.modular.jms.MessageTypes;
import com.mainbo.modular.jms.model.*;
import com.mainbo.modular.system.model.PtConfig;
import com.mainbo.modular.system.model.PtOrg;
import com.mainbo.modular.system.model.meta.ConfigConstants;
import com.mainbo.modular.system.model.meta.MetaKeys;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.model.meta.vo.Meta;
import com.mainbo.modular.system.model.vo.SchoolYearVo;
import com.mainbo.modular.system.service.IPtConfigService;
import com.mainbo.modular.system.service.IPtSchoolYearTermManageService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author xww
 * @Description 学年学期管理
 * @Date 2020/3/9   15:59
 **/
@Controller
@RequestMapping("/ptSchoolYearTermManage")
public class PtSchoolYearTermManageController extends BaseController {
    private static final Logger logger = LoggerFactory
            .getLogger(PtSchoolYearTermManageController.class);
    private String PREFIX = "/system/ptSchoolYearTerm/";
    @Resource
    private IPtSchoolYearTermManageService schoolYearTermManageService;
    @Resource
    private IPtConfigService ptConfigService;
    /**
     * 学年首页
     *
     * @param model
     *          Model
     * @return String
     */
    @RequestMapping("")
    public String schoolyearIndex(Model model) {
        PtOrg org= ShiroKit.getSessionAttr(SessionKey.CURRENT_ORG);
        if ((org == null)) {
            model.addAttribute("orgId","0");
            model.addAttribute("areaId",0);
            return PREFIX + "schoolYear_org.html";
        }
        model.addAttribute("orgId",org.getId());
        model.addAttribute("areaId",org.getAreaId());
        return PREFIX + "schoolYear_list.html";
    }

    @RequestMapping("findList")
    @ResponseBody
    public Object dataIndex(String orgId, Integer areaId) {
        List<SchoolYearVo> schoolYearVos=new ArrayList<>();
        if (StringUtils.isNotEmpty(orgId)) {
            schoolYearVos =schoolYearTermManageService.getSchoolYearAndTermByOrg(orgId);

        } else if (areaId != null) {
            schoolYearVos =schoolYearTermManageService.getSchoolYearAndTermByArea(areaId);
        }
        return schoolYearVos;
    }

    /**
     * 编辑学年
     *
     * @param m
     *          Model
     * @param id
     *          学年id
     * @param orgId
     *          学校id
     * @param areaId
     *          区域id
     * @return String
     */
    @RequestMapping("/schoolyear/toAddOrEdit/{id}")
    public String editSchoolYear(Model m, @PathVariable Integer id, String orgId, Integer areaId) {
        m.addAttribute("orgId", orgId);
        m.addAttribute("areaId", areaId);
        if (id != null && -1 != id.intValue()) {
            Meta meta = MetaUtils.getMeta(id);
            m.addAttribute("vo", new SchoolYearVo(meta));

        }
        int start = MetaUtils.getSchoolYearProvider().getCurrentSchoolYear();
        m.addAttribute("startYear", start);
        m.addAttribute("endYear", start + 1);
        try {
            String value = ConfigUtils.readStaticConfig(MetaKeys.SCHOOL_YEAR_SPLIT,
                    "09.01");
            if (value != null) {
                m.addAttribute("start", start + "." + value);
                String startStr = value;
                DateFormat df = new SimpleDateFormat("MM.dd");
                Date startDate = df.parse(startStr);
                Calendar c = Calendar.getInstance();
                c.setTime(startDate);
                c.add(Calendar.DAY_OF_MONTH, -1);
                Date time = c.getTime();
                String endTime = df.format(time);
                m.addAttribute("end", (start + 1) + "." + endTime);
            }
        } catch (Exception e) {
            logger.info("parse schoolyear failed");
        }
        if (id==-1){
            return PREFIX+"schoolYear_add.html";
        }else {
            return PREFIX+"schoolYear_edit.html";
        }
    }

    /**
     * 保存学年
     *
     * @param vo
     *          SchoolYearVo
     * @return JuiResult
     */
    @RequestMapping("/schoolyear/saveOrUpdate")
    @ResponseBody
    public Result editSchoolYear(SchoolYearVo vo) {
        Result rs = new Result();
        if (vo.getName().substring(0,1).equals("-")||(vo.getName().substring(vo.getName().length()-1,vo.getName().length()).equals("-"))){
            rs.setMsg("学年名称不允许为空！");
            rs.setCode(Result.FAIL);
            return rs;
        }

        if (vo.getId() == null) {
            EntityWrapper<PtConfig> model = new EntityWrapper<>();
            model.eq("code",ConfigConstants.SCHOOLYEAR_CODE);
            model.eq("name",vo.getName());
            if (StringUtils.isNotEmpty(vo.getOrgId())) {
                model.eq("type",ConfigConstants.ORG_TYPE);
                model.eq("org_id",vo.getOrgId());

            } else if (vo.getAreaId() != null) {
                model.eq("type",ConfigConstants.AREA_TYPE);
                model.eq("area_id",vo.getAreaId());
            }
            PtConfig ptConfig = ptConfigService.selectOne(model);
            if (ptConfig!=null){
                rs.setMsg("该名称在该机构下已创建过！");
                rs.setCode(Result.FAIL);
                return rs;
            }
            schoolYearTermManageService.saveSchoolYear(vo);
        } else {
            schoolYearTermManageService.updateSchoolYear(vo);
        }
        rs.setCode(Result.SUCCESS);
        rs.setMsg("操作成功");
        return rs;
    }
    /**
     * 编辑系统学期
     *
     * @param m
     *          Model
     * @param id
     *          学期id
     * @return String
     */
    @RequestMapping("/schoolyear/editTerm/{id}")
    public String manageSchoolTerm(Model m, @PathVariable Integer id) {
        m.addAttribute("schoolYearId", id);
//        if (id != null && -1 != id.intValue()) {
//            Meta meta = MetaUtils.getMeta(id);
//            m.addAttribute("vo", new SchoolYearVo(meta));
//
//        }
        return PREFIX+"schoolTerm_list.html";
    }

    /**
     * 查找系统学期
     *
     *          Model
     * @param schoolYearId
     *          学年id
     * @return String
     */
    @RequestMapping("/schoolyear/findTermList")
    @ResponseBody
    public Object findTermList(Integer schoolYearId) {
        List<SchoolYearVo> terms=schoolYearTermManageService.getSchoolTerm(schoolYearId);
        return terms;
    }

    /**
     * 编辑学期
     *
     * @param m
     *          Model
     * @param id
     *          学期id
     * @param schoolYearId
     *          学年id
     * @return String
     */
    @RequestMapping("/schoolterm/edit/{id}")
    public String editSchoolTerm(Model m, @PathVariable Integer id,
                                 Integer schoolYearId) {
        Meta sy = MetaUtils.getMeta(schoolYearId);
        if (sy != null) {
            m.addAttribute("schoolYear", new SchoolYearVo(sy));
        }
        m.addAttribute("sysTerms", MetaUtils.listMeta(ConfigConstants.TERM_CODE));
        if (id != null && id.intValue() != -1) {
            SchoolYearVo term = schoolYearTermManageService.getTerm(id);
            m.addAttribute("term", term);
           return PREFIX+"schoolTerm_edit.html";
        }

        return PREFIX+"schoolTerm_add.html";
    }
    /**
     * 保存学期
     *
     * @param vo
     *          SchoolYearVo
     * @return JuiResult
     */
    @RequestMapping("/schoolterm/save")
    @ResponseBody
    private Result saveSchoolTerm(SchoolYearVo vo) {
        Result rs = new Result();
        rs.setCode(Result.SUCCESS);
        if (!validateTermVo(vo, rs)) {
            rs.setCode(Result.FAIL);
            rs.setMsg("起始时间必须早于结束时间，且教学日期必须在学期日期范围内！");
            return rs;
        }

        if (vo.getTermId() != null) {
            schoolYearTermManageService.updateSchoolTerm(vo);
        } else {
            if (!schoolYearTermManageService.saveSchoolTerm(vo)) {
                rs.setCode(Result.FAIL);
                rs.setMsg("该学期已存在！");
                return rs;
            }
        }
        rs.setMsg("操作成功");
        return rs;
    }

    private boolean validateTermVo(SchoolYearVo vo, Result rs) {
        int weeks = 0;
        try {
            Date start = DateUtils.parseDate(vo.getTermStartTime(), "yyyy.MM.dd");
            Calendar startCal = Calendar.getInstance();
            startCal.setFirstDayOfWeek(Calendar.MONDAY);
            startCal.setTime(start);

            Date end = DateUtils.parseDate(vo.getTermEndTime(), "yyyy.MM.dd");
            Calendar endCal = Calendar.getInstance();
            endCal.setFirstDayOfWeek(Calendar.MONDAY);
            endCal.setTime(end);
            int startWk = startCal.get(Calendar.DAY_OF_WEEK) + 6;
            int wks = (int) ((end.getTime() - start.getTime()) / (1000 * 3600 * 24));
            int mod = wks % 7;
            weeks = wks / 7 + 1;
            if ((startWk > 7 ? startWk % 7 : startWk) + mod > 7) {
                weeks = weeks + 1;// 过了周六
            }

            Date tstart = DateUtils.parseDate(vo.getTeachStartTime(), "yyyy.MM.dd");
            Date tend = DateUtils.parseDate(vo.getTeachEndTime(), "yyyy.MM.dd");
            if (start.after(tstart) || start.after(end) || end.before(tend)
                    || tstart.after(tend)) {
                return false;
            }
        } catch (ParseException e) {
            logger.error("date parse failed ,start: {}, end : {}",
                    vo.getTeachStartTime(), vo.getTermEndTime());
        }
        vo.setWeeks(weeks);
        return true;
    }


}
